package logic

import (
	"context"
	"fmt"
	"net/http"
	"order_srv/order"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AlipayCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAlipayCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AlipayCallbackLogic {
	return &AlipayCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AlipayCallbackLogic) AlipayCallback(w http.ResponseWriter, r *http.Request) (resp *types.AlipayCallbackResponse, err error) {
	// todo: add your logic here and delete this line

	fmt.Println("支付宝回调")
	fmt.Println(r)
	fmt.Println("支付宝回调")

	orderSn := r.FormValue("out_trade_no")
	status := r.FormValue("trade_status")

	/*	WAIT_BUYER_PAY	//交易创建，等待买家付款。
		TRADE_CLOSED	//未付款交易超时关闭，或支付完成后全额退款。
		TRADE_SUCCESS	//交易支付成功。
		TRADE_FINISHED	//交易结束，不可退款。
	*/

	if status == "WAIT_BUYER_PAY" {
		l.svcCtx.OrderSrv.UpdateOrderStatus(l.ctx, &order.UpdateOrderStatusRequest{
			OrderSn: orderSn,
			Status:  1,
		})
	} else if status == "TRADE_CLOSED" {
		l.svcCtx.OrderSrv.UpdateOrderStatus(l.ctx, &order.UpdateOrderStatusRequest{
			OrderSn: orderSn,
			Status:  2,
		})
	} else if status == "TRADE_SUCCESS" {
		l.svcCtx.OrderSrv.UpdateOrderStatus(l.ctx, &order.UpdateOrderStatusRequest{
			OrderSn: orderSn,
			Status:  3,
		})
	} else if status == "TRADE_FINISHED" {
		l.svcCtx.OrderSrv.UpdateOrderStatus(l.ctx, &order.UpdateOrderStatusRequest{
			OrderSn: orderSn,
			Status:  4,
		})
	}

	w.Write([]byte("success"))

	return
}
